package cn.yuan.data.product;

import cn.common.constant.RabbitConstants;
import cn.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
@Slf4j
public class MatchProducer {
    private final RabbitTemplate rabbitTemplate;

    public MatchProducer(RabbitTemplate rabbit) {
        this.rabbitTemplate = rabbit;
        initCallbacks();
    }

    public void initCallbacks(){
        rabbitTemplate.setConfirmCallback((correlation,  ack, cause) -> {
            if (correlation != null) {
                log.info("Correlation  ID: {}", correlation.getId());
                if (!ack) {
                    log.error("putMainEntrustMatch 消息未到达Exchange: {}", cause);
                }
            }
        });
        // 路由到Queue失败回调（需配置mandatory=true）
        rabbitTemplate.setReturnsCallback(returned  -> {
            log.error("putMainEntrustMatch 消息路由失败: {}", returned.getMessage());
            log.error("putMainEntrustMatch Exchange:  {}, RoutingKey: {}", returned.getExchange(),  returned.getRoutingKey());
        });
    }

    public void putMainEntrustMatch(String content) {
        try {
            CorrelationData correlation = new CorrelationData(UUID.randomUUID().toString());
            rabbitTemplate.convertAndSend(RabbitConstants.MATCH_PRODUCER_EXCHANGE_PUT,RabbitConstants.MATCH_PRODUCER_ROUTING_PUT,content,correlation);
            log.info("putMainEntrustMatch消息已发送，ID: {}", correlation.getId());
        } catch (RuntimeException e) {
            log.error("putMainEntrustMatch消息发送异常", e);
            throw new BusinessException( "putMainEntrustMatch消息发送失败");
        }
    }

    public void putProjectEntrustMatch(String content) {
        try {
            CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
            rabbitTemplate.convertAndSend(RabbitConstants.ENTRUST_PROJECT_MATCH_PUT,RabbitConstants.ENTRUST_PROJECT_MATCH_ROUTINGKEY_PUT,content,correlationId);
        } catch (RuntimeException e) {
            log.error("putMainEntrustMatch消息发送异常", e);
            throw new BusinessException( "putMainEntrustMatch消息发送失败");
        }
    }
}
